package com.jeedcp.gen.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jeedcp.gen.dao.DibotColumDao;
import com.jeedcp.gen.dao.TableMapper;
import com.jeedcp.gen.entity.GenColumn;
import com.jeedcp.gen.entity.ItemNameValue;
import com.jeedcp.gen.entity.Menudate;
import com.jeedcp.gen.entity.Metadate;
import com.jeedcp.gen.model.GenTable;
import com.jeedcp.gen.model.GenTableColumn;
import com.jeedcp.gen.service.CommonService;
import com.jeedcp.gen.utils.DBUtil;
import com.jeedcp.gen.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.*;

@RestController
@RequestMapping("/devtools/v1/common")
public class CommonController {
    @Autowired
    TableMapper tableMapper;
    @Autowired
    DibotColumDao dibotColumDao;
    @Autowired
    CommonService commonService;

    @RequestMapping(value = "/tables", method = RequestMethod.GET)
    public R getTables() {
        List<GenTable> result = new ArrayList<>();
        List<Map> tables = tableMapper.listTable();
        for (Map map : tables) {
            GenTable genTable = new GenTable();
            genTable.setActive(true);
            genTable.setEditable(true);
            genTable.setGenerateCommonCodes(false);
            genTable.setModelName("数据表");
            genTable.setObjName((String) map.get("TABLE_COMMENT"));
            genTable.setTableName((String) map.get("TABLE_NAME"));
            result.add(genTable);
        }
        return R.ok().put("data", result);
    }

    @RequestMapping(value = "/columns", method = RequestMethod.GET)
    public R getTableColumn(String tableName) throws Exception {
        String sql = "select t.table_name from information_schema.TABLES t where t.TABLE_SCHEMA ='jeedcp' and t.TABLE_NAME ='gen_column'";
        List<String> list = DBUtil.executeQueryStr(sql);
        if (list.size() == 0) {
            commonService.createdibootcolumn();
        }

        List<Map> tableColumn = tableMapper.listTableColumn(tableName);
        List<GenTableColumn> result = new ArrayList<>();
        for (Map map : tableColumn) {
            GenColumn genColumn = dibotColumDao.selectOne(new QueryWrapper<GenColumn>().eq("table_name", (String) map.get("TABLE_NAME")).eq("col_name", (String) map.get("COLUMN_NAME")));
            GenTableColumn genTableColumn = new GenTableColumn();
            genTableColumn.setActive(true);
            genTableColumn.setColIndex(Integer.valueOf(String.valueOf(map.get("ORDINAL_POSITION"))) - 1);
            genTableColumn.setColType((String) map.get("COLUMN_TYPE"));
            genTableColumn.setTableName((String) map.get("TABLE_NAME"));
            genTableColumn.setColName((String) map.get("COLUMN_NAME"));
            if (genTableColumn.getColName().equals("id")) {
                genTableColumn.setPrimaryKey(true);
            } else {
                genTableColumn.setPrimaryKey(false);
            }
            String colLength = (String) map.get("COLUMN_TYPE");
            if (colLength.contains(",")) {
                colLength = colLength.substring(colLength.indexOf("(") + 1, colLength.indexOf(","));
            } else if (colLength.contains("(") && colLength.contains(")")) {
                colLength = colLength.substring(colLength.indexOf("(") + 1, colLength.indexOf(")"));
            } else {
                colLength = "0";
            }
            genTableColumn.setColLength(Integer.valueOf(colLength));
            genTableColumn.setFieldLabel((String) map.get("COLUMN_COMMENT"));
            if (map.get("COLUMN_DEFAULT") == null) {
                genTableColumn.setDefaultValue("");
            } else {
                genTableColumn.setDefaultValue((String) map.get("COLUMN_DEFAULT"));
            }
            genTableColumn.setFieldName((String) map.get("COLUMN_NAME"));
            if (String.valueOf(map.get("DATA_TYPE")).contains("varchar")
                    ||String.valueOf(map.get("DATA_TYPE")).contains("text")
                    ||String.valueOf(map.get("DATA_TYPE")).contains("char")) {
                genTableColumn.setFieldPackagingType("String");
            } else if (String.valueOf(map.get("DATA_TYPE")).contains("double") || String.valueOf(map.get("DATA_TYPE")).contains("decimal")) {
                genTableColumn.setFieldPackagingType("Double");
            } else if (String.valueOf(map.get("DATA_TYPE")).contains("timestamp") || String.valueOf(map.get("DATA_TYPE")).contains("date")) {
                genTableColumn.setFieldPackagingType("Date");
            } else if (String.valueOf(map.get("DATA_TYPE")).contains("bigint") || String.valueOf(map.get("DATA_TYPE")).equals("int")) {
                genTableColumn.setFieldPackagingType("Long");
            } else if (String.valueOf(map.get("DATA_TYPE")).contains("smallint")) {
                genTableColumn.setFieldPackagingType("Integer");
            } else if (String.valueOf(map.get("DATA_TYPE")).contains("tinyint")) {
                genTableColumn.setFieldPackagingType("Boolean");
            } else {
                genTableColumn.setFieldPackagingType("");
            }
            if ("NO".equals(map.get("IS_NULLABLE"))) {
                genTableColumn.setNotnull(1);
            } else {
                genTableColumn.setNotnull(0);
            }
            if (genTableColumn.getFieldPackagingType().contains("Date")) {
                if (genTableColumn.getColType().contains("timestamp")) {
                    genTableColumn.setExtensionList("yyyy-MM-dd HH:mm");
                } else {
                    genTableColumn.setExtensionList("yyyy-MM-dd");
                }
            } else if (genTableColumn.getFieldPackagingType().contains("decimal")) {
                genTableColumn.setExtensionList("fixed");
            } else if (genTableColumn.getFieldPackagingType().contains("double")) {
                genTableColumn.setExtensionList("float");
            } else if (genTableColumn.getColType().contains("unsigned")) {
                genTableColumn.setExtensionList("unsigned");
            } else {
                genTableColumn.setExtensionList("");
            }
            if (map.get("NUMERIC_SCALE") == null) {
                genTableColumn.setDecimal(0);
            } else {
                genTableColumn.setDecimal(Integer.valueOf(String.valueOf(map.get("NUMERIC_SCALE"))));
            }

            genTableColumn.setHasReference(false);
            genTableColumn.setHasReferenceTable(false);

            if (genColumn != null) {
                genTableColumn.setIsInsert(genColumn.getIsInsert());
                genTableColumn.setIsList(genColumn.getIsList());
                genTableColumn.setIsQuery(genColumn.getIsQuery());
                genTableColumn.setQueryType(genColumn.getQueryType());
                genTableColumn.setFormType(genColumn.getFormType());
                genTableColumn.setAsColumn(genColumn.getAsColumn());
                genTableColumn.setExtensionList(genColumn.getExtensions());
                genTableColumn.setRefType(genColumn.getRefType());
                genTableColumn.setRefTable(genColumn.getRefTable());
                genTableColumn.setRefColumn(genColumn.getRefColumn());
            } else {
                genTableColumn.setIsInsert(0);
                genTableColumn.setIsList(0);
                genTableColumn.setIsQuery(0);
                genTableColumn.setQueryType("");
                genTableColumn.setFormType("NONE");
                genTableColumn.setAsColumn("");
                genTableColumn.setRefType("");
                genTableColumn.setRefTable("");
                genTableColumn.setRefColumn("");
                if (genTableColumn.getColName().contains("time")) {
                    genTableColumn.setExtensionList("yyyy-MM-dd HH:mm");
                } else {
                    genTableColumn.setExtensionList("");
                }
            }

            if (genTableColumn.getColName().equals("id")) {
                genTableColumn.setExtensionList("unsigned");
            }

            genTableColumn.setTableColumns(new ArrayList<>());
            result.add(genTableColumn);
        }
        return R.ok().put("data", result);
    }

    /**
     * 修改表
     */
    @RequestMapping("/updatecolumns")
    // @RequiresPermissions("cleancard:update")

    public R update(@RequestBody List<GenTableColumn> genTableColumnList) throws Exception {


        R r = commonService.updatetable(genTableColumnList);

        return r;
    }

    @RequestMapping(value = "/metadataList", method = RequestMethod.GET)
    public R getMetadataList() throws Exception {
        String sql = "SELECT type,item_name FROM `metadata` where parent_id=0";
        List<Map<String, Object>> list = DBUtil.query(sql);


        Map map = new HashMap<>();
        map.put("data", list);
        return R.ok(map);
    }

    /**
     * 修改表
     */
    @RequestMapping("/metadata")
    // @RequiresPermissions("cleancard:update")

    public R metadata(@RequestBody Metadate metadate) {

        String sql3 = "SELECT * from metadata where item_name='" + metadate.getItemName() + "' and type='" + metadate.getType() + "'";
        List<Map<String, Object>> stringList0 = null;
        try {
            stringList0 = DBUtil.query(sql3);
        } catch (SQLException e) {
            return R.ok("新增元数据失败");
        }
        if (stringList0.size() > 0) {
            return R.ok("数据库中已存在！");
        }
        String sql1 = "INSERT INTO metadata (parent_id, type, item_name,comment) VALUES ('0', '" + metadate.getType() + "', '" + metadate.getItemName() + "','" + metadate.getCommon() + "')";
        try {
            DBUtil.executeUpdateFH(sql1);
        } catch (Exception e) {
            return R.ok("新增元数据失败");
        }
        String sql2 = "SELECT * from metadata where item_name='" + metadate.getItemName() + "' and type='" + metadate.getType() + "'";
        List<Map<String, Object>> stringList = null;
        try {
            stringList = DBUtil.query(sql2);
        } catch (SQLException e) {
            return R.ok("新增元数据失败");
        }
        if (stringList.size() > 1) {
            return R.ok("数据库中已存在！");
        }
        for (ItemNameValue itemNameValue : metadate.getChildren()) {
            String sql = "INSERT INTO metadata (parent_id, type, item_name,item_value) VALUES ('" + stringList.get(0).get("id") + "', '" + metadate.getType() + "', '" + itemNameValue.getItemName() + "','" + itemNameValue.getItemValue() + "')";
            try {
                DBUtil.executeUpdateFH(sql);
            } catch (ClassNotFoundException e) {
                return R.ok("新增元数据失败");
            } catch (SQLException e) {
                return R.ok("新增元数据失败");
            }
        }


        return R.ok("新增元数据成功");
    }

    @RequestMapping("/menu")
    public R menu(@RequestBody Menudate menudate) {
        String sql3 = "SELECT * from menu where name='" + menudate.getName() + "' and parent_id='0'";
        List<Map<String, Object>> stringList0 = null;
        try {
            stringList0 = DBUtil.query(sql3);
        } catch (SQLException e) {
            return R.ok("新增菜单失败");
        }
        if (stringList0.size() > 0) {
            return R.ok("菜单已存在！");
        }
        String sql1 = "INSERT INTO menu (parent_id, type,application, name,icon,sort_id) VALUES ('0', 'PC', 'MS','" + menudate.getName() + "','"+menudate.getIcon()+"','999')";
        try {
            DBUtil.executeUpdateFH(sql1);
        } catch (Exception e) {
            return R.ok("新增菜单失败");
        }

        return R.ok("新增菜单成功");
    }

    @RequestMapping("/menus")
    public R menus() {
        String sql3 = "SELECT * from menu where  parent_id='0'";
        List<Map<String, Object>> stringList0 = null;
        try {
            stringList0 = DBUtil.query(sql3);
        } catch (SQLException e) {
            return R.ok("查询菜单失败");
        }
        Map map=new HashMap();
        map.put("data",stringList0);
        map.put("msg","操作成功");
        return R.ok(map);
    }
}
